import { DownOutlined, PlusOutlined } from '@ant-design/icons';
import { Button, Divider, Dropdown, Menu, message, Avatar } from 'antd';
import React, { useState, useRef, useEffect } from 'react';
import { Dispatch } from 'redux';
import { RouteChildrenProps } from 'react-router';
import { connect } from 'dva';
import { ConnectProps, ConnectState } from '@/models/connect';
import ProTable, { ProColumns, ActionType, RequestData } from '@ant-design/pro-table';

import { post } from '@/utils/request';
import { confirm, toast, msgLoading, getEnumFromSelectMap } from '@/utils/utils';
import * as api from '@/constants/api';
import Cookies from 'js-cookie';
import { LOGIN_ROLE_KEY, roles } from '@/constants/index';
import { roleList, sexList } from '@/constants/selectMaps';
import EditForm from './components/EditForm';
import { UserItem, UserListParams } from '../../types/user';
import { CurrentUser } from '../../models/user';

const roleEnum = getEnumFromSelectMap(roleList);
const sexEnum = getEnumFromSelectMap(sexList);

interface ClsProps extends RouteChildrenProps {
  dispatch: Dispatch<any>;
  currentUser?: Partial<CurrentUser>;
}

const TableList: React.FC<ClsProps> = props => {
  const [editDialogVisible, setEditDialogVisible] = useState<boolean>(false);
  const [editRow, setEditRow] = useState({});
  const actionRef = useRef<ActionType>();
  const [schoolList, setSchoolList] = useState([
    { value: '1', label: '类型1', eduSystem: '' },
    { value: '2', label: '类型2', eduSystem: '' },
  ]);

  const isSuperAdmin = Cookies.get(LOGIN_ROLE_KEY) === roles.admin;

  /**
   * 查询
   */
  const queryList = async (params?: UserListParams): Promise<RequestData<UserItem>> => {
    params = params || {};

    const res: ServerListData = await post(api.GET_LIST, {
      ...params,
      pageNo: params.current,
    });
    return {
      data: res.rows,
      success: true,
      total: res.total,
    };
  };

  /**
   *  删除
   */
  const handleRemove = (row: UserItem) => {
    confirm('确定要删除吗？', () => {
      post(api.COMMON_OK, { _id: row._id }).then(() => {
        toast('删除成功');
        // eslint-disable-next-line no-unused-expressions
        actionRef.current && actionRef.current.reload();
      });
    });
  };

  /**
   * table的列配置
   */
  const columns: ProColumns<UserItem>[] = [
    {
      title: '种类',
      dataIndex: 'typeId',
      valueEnum: schoolList.reduce((total, now) => {
        total[now.value] = now.label;
        return total;
      }, {}),
      filters: [],
      hideInSearch: !isSuperAdmin,
      hideInTable: !isSuperAdmin,
    },
    // 账号
    {
      title: '账号',
      dataIndex: 'account',
      hideInSearch: true,
    },
    // 姓名
    {
      title: '姓名',
      dataIndex: 'name',
    },
    // 角色
    {
      title: '角色',
      dataIndex: 'role',
      filters: [],
      valueEnum: roleEnum,
      hideInSearch: true,
    },
    // 头像
    {
      title: '头像',
      dataIndex: 'avatar',
      render: (text, record, index, action) => <Avatar src={record.avatar} />,
      hideInSearch: true,
    },
    // 性别
    {
      title: '性别',
      dataIndex: 'sex',
      filters: [],
      valueEnum: sexEnum,
      hideInSearch: true,
    },
    // 手机号码
    {
      title: '手机号码',
      dataIndex: 'phone',
    },
    // 邮箱
    {
      title: '邮箱',
      dataIndex: 'email',
    },
    // 操作
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => (
        <>
          {record.role !== roles.admin && (
            <a
              onClick={() => {
                setEditRow({ ...record });
                setEditDialogVisible(true);
              }}
            >
              修改
            </a>
          )}
          {record.role !== roles.admin && (
            <a
              onClick={() => {
                handleRemove(record);
              }}
              style={{ color: '#f5222d' }}
            >
              删除
            </a>
          )}
        </>
      ),
    },
  ];

  return (
    <>
      <ProTable<UserItem>
        headerTitle=""
        actionRef={actionRef}
        rowKey="key"
        toolBarRender={(action, { selectedRows }) => [
          <Button
            icon={<PlusOutlined />}
            type="primary"
            onClick={() => {
              setEditRow({});
              setEditDialogVisible(true);
            }}
          >
            新建
          </Button>,
        ]}
        // table 工具菜单
        options={{ fullScreen: false, reload: false, setting: false, density: false }}
        // table顶部描述内容
        tableAlertRender={(selectedRowKeys, selectedRows) => false}
        request={params => queryList(params)}
        columns={columns}
        pagination={{ defaultPageSize: 10 }}
      />
      <EditForm
        schoolList={schoolList}
        isSuperAdmin={isSuperAdmin}
        visible={editDialogVisible}
        editRow={editRow}
        onCancel={() => setEditDialogVisible(false)}
        onSuc={() => {
          setEditDialogVisible(false);
          // eslint-disable-next-line no-unused-expressions
          actionRef.current?.reload();
        }}
      />
    </>
  );
};

// export default TableList;
export default connect(({ user }: ConnectState) => ({
  currentUser: user.currentUser,
}))(TableList);
